package com.lib093.rich.activity

import android.app.Activity
import android.content.Context
import android.content.Intent
import android.graphics.Color
import android.os.Bundle
import android.text.Editable
import android.text.Html
import android.text.TextUtils
import android.text.TextWatcher
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.PopupWindow
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import com.lib093.rich.R
import com.lib093.rich.bean.RichContent
import com.lib093.rich.utils.CommonPopupWindow
import com.lib093.rich.utils.KeyBoardUtils
import com.lib093.rich.utils.RichUtils
import com.lib093.rich.view.RichEditor
import com.lzy.imagepicker.ImagePicker
import com.lzy.imagepicker.bean.ImageItem
import com.lzy.imagepicker.ui.ImageGridActivity
import com.yalantis.ucrop.UCrop.EXTRA_OUTPUT_URI
import com.yalantis.ucrop.UCropActivity
import kotlinx.android.synthetic.main.activity_publish.*

class PublishActivity : AppCompatActivity(), View.OnClickListener {
    private val selectImages: ArrayList<ImageItem> = ArrayList<ImageItem>()

    private var popupWindow //编辑图片的pop
            : CommonPopupWindow? = null
    private var currentUrl = ""

    private var imgList = ArrayList<String>();

    private var maxNum = 6

    //title = "<h1 style=\"text-align:center;\">"+title+"</h1>";
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_publish)
        initClick();
        initPop()
        initEditor()
        maxNum = intent.getIntExtra("maxNum",6)
        intent.extras?.let {
            var data = intent.extras?.getSerializable("data") as RichContent
            val title = data.title
            val content = data.conetnt
            edit_name.setText(title)
            rich_Editor.html = content
            txt_publish.setSelected(true)
            txt_publish.setEnabled(true)
        }
    }


    private fun initEditor() {
        //输入框显示字体的大小
        rich_Editor.setEditorFontSize(18)
        //输入框显示字体的颜色
        rich_Editor.setEditorFontColor(resources.getColor(R.color.black1b))
        //输入框背景设置
        rich_Editor.setEditorBackgroundColor(Color.WHITE)
        //输入框文本padding
        rich_Editor.setPadding(10, 10, 10, 10)
        //输入提示文本
        rich_Editor.setPlaceholder("请开始你的创作！~")

        //文本输入框监听事件
        rich_Editor.setOnTextChangeListener(object : RichEditor.OnTextChangeListener {
            override fun onTextChange(text: String?) {
                Log.e("富文本文字变动", text!!)
                if (TextUtils.isEmpty(edit_name.getText().toString().trim())) {
                    txt_publish.setSelected(false)
                    txt_publish.setEnabled(false)
                    return
                }
                if (TextUtils.isEmpty(text)) {
                    txt_publish.setSelected(false)
                    txt_publish.setEnabled(false)
                } else {
                    if (TextUtils.isEmpty(Html.fromHtml(text))) {
                        txt_publish.setSelected(false)
                        txt_publish.setEnabled(false)
                    } else {
                        txt_publish.setSelected(true)
                        txt_publish.setEnabled(true)
                    }
                }
            }

        })
        edit_name.addTextChangedListener(object : TextWatcher {
            override fun beforeTextChanged(
                s: CharSequence,
                start: Int,
                count: Int,
                after: Int
            ) {
            }

            override fun onTextChanged(
                s: CharSequence,
                start: Int,
                before: Int,
                count: Int
            ) {
            }

            override fun afterTextChanged(s: Editable) {
                val html: String? = rich_Editor.html
                if (TextUtils.isEmpty(html)) {
                    txt_publish.setSelected(false)
                    txt_publish.setEnabled(false)
                    return
                } else {
                    if (TextUtils.isEmpty(Html.fromHtml(html))) {
                        txt_publish.setSelected(false)
                        txt_publish.setEnabled(false)
                        return
                    } else {
                        txt_publish.setSelected(true)
                        txt_publish.setEnabled(true)
                    }
                }
                if (TextUtils.isEmpty(s.toString())) {
                    txt_publish.setSelected(false)
                    txt_publish.setEnabled(false)
                } else {
                    txt_publish.setSelected(true)
                    txt_publish.setEnabled(true)
                }
            }
        })
        rich_Editor.setOnDecorationChangeListener(object : RichEditor.OnDecorationStateListener {
            override fun onStateChangeListener(text: String?, types: List<RichEditor.Type>?) {
                val flagArr =
                    ArrayList<String>()
                for (i in types?.indices!!) {
                    flagArr.add(types[i].name)
                }
                if (flagArr.contains("BOLD")) {
                    button_bold.setImageResource(R.mipmap.bold_)
                } else {
                    button_bold.setImageResource(R.mipmap.bold)
                }
                if (flagArr.contains("UNDERLINE")) {
                    button_underline.setImageResource(R.mipmap.underline_)
                } else {
                    button_underline.setImageResource(R.mipmap.underline)
                }
                if (flagArr.contains("ORDEREDLIST")) {
                    button_list_ul.setImageResource(R.mipmap.list_ul)
                    button_list_ol.setImageResource(R.mipmap.list_ol_)
                } else {
                    button_list_ol.setImageResource(R.mipmap.list_ol)
                }
                if (flagArr.contains("UNORDEREDLIST")) {
                    button_list_ol.setImageResource(R.mipmap.list_ol)
                    button_list_ul.setImageResource(R.mipmap.list_ul_)
                } else {
                    button_list_ul.setImageResource(R.mipmap.list_ul)
                }
            }

        })
        rich_Editor.setImageClickListener(object : RichEditor.ImageClickListener {
            override fun onImageClick(imageUrl: String?) {
                currentUrl = imageUrl!!
                popupWindow!!.showBottom(ly, 0.5f)
            }
        })
    }


    private fun initPop() {
        val view: View =
            LayoutInflater.from(this@PublishActivity).inflate(R.layout.newapp_pop_picture, null)
        view.findViewById<View>(R.id.linear_cancle)
            .setOnClickListener { v: View? -> popupWindow?.dismiss() }
        view.findViewById<View>(R.id.linear_editor)
            .setOnClickListener { v: View? ->
                //编辑图片
                val intent =
                    Intent(this@PublishActivity, UCropActivity::class.java)
                intent.putExtra("filePath", currentUrl)
                val destDir = filesDir.absolutePath.toString()
                val fileName =
                    "rich" + System.currentTimeMillis() + ".jpg"
                intent.putExtra("outPath", destDir + fileName)
                startActivityForResult(intent, 11)
                popupWindow!!.dismiss()
            }
        view.findViewById<View>(R.id.linear_delete_pic)
            .setOnClickListener { v: View? ->
                //删除图片
                val removeUrl: String =
                    "<img src=\"$currentUrl\" alt=\"dachshund\" width=\"100%\"><br>"
                val newUrl: String? = rich_Editor.html?.replace(removeUrl, "")
                currentUrl = ""
                imgList.remove(currentUrl)
                rich_Editor.html = newUrl
                rich_Editor.redo()
                if (RichUtils.isEmpty(rich_Editor.html)) {
                    rich_Editor.html = ""
                }
                popupWindow?.dismiss()
            }
        popupWindow = CommonPopupWindow.Builder(this@PublishActivity)
            .setView(view)
            .setWidthAndHeight(
                ViewGroup.LayoutParams.MATCH_PARENT,
                ViewGroup.LayoutParams.WRAP_CONTENT
            )
            .setOutsideTouchable(true) //在外不可用手指取消
            .setAnimationStyle(R.style.pop_animation) //设置popWindow的出场动画
            .create()
        popupWindow!!.setOnDismissListener(PopupWindow.OnDismissListener {
            rich_Editor.setInputEnabled(
                true
            )
        })
    }

    fun initClick() {
        txt_finish.setOnClickListener(this)
        txt_publish.setOnClickListener(this)
        button_rich_do.setOnClickListener(this)
        button_rich_undo.setOnClickListener(this)
        button_bold.setOnClickListener(this)
        button_underline.setOnClickListener(this)
        button_list_ul.setOnClickListener(this)
        button_list_ol.setOnClickListener(this)
        button_image.setOnClickListener(this)
    }

    override fun onClick(v: View) {
        when (v.id) {
            R.id.txt_finish -> finish()
            R.id.txt_publish -> {
                var list =   rich_Editor.html?.let {
                    RichUtils.returnImageUrlsFromHtml(it) }
                var data = RichContent(edit_name.getText().toString().trim(),rich_Editor.html,list );
                var bundle:Bundle = Bundle()
                    bundle.putSerializable("data",data)
                intent.putExtras(bundle)
                setResult(Activity.RESULT_OK, intent)
                finish()
            }
            R.id.button_rich_do ->                 //反撤销
                rich_Editor.redo()
            R.id.button_rich_undo ->                 //撤销
                rich_Editor.undo()
            R.id.button_bold -> {
                //加粗
                againEdit()
                rich_Editor.setBold()
            }
            R.id.button_underline -> {
                //加下划线
                againEdit()
                rich_Editor.setUnderline()
            }
            R.id.button_list_ul -> {
                //加带点的序列号
                againEdit()
                rich_Editor.setBullets()
            }
            R.id.button_list_ol -> {
                //加带数字的序列号
                againEdit()
                rich_Editor.setNumbers()
            }
            R.id.button_image -> {
                if (!TextUtils.isEmpty(rich_Editor.html)) {
                    val arrayList: ArrayList<String> =
                        RichUtils.returnImageUrlsFromHtml(rich_Editor.html)
                    if (arrayList != null && arrayList.size >= maxNum) {
                        Toast.makeText(this@PublishActivity, "最多添加${maxNum}张照片~", Toast.LENGTH_SHORT).show()
                        return
                    }
                }
                selectImage(104, selectImages)
                KeyBoardUtils.closeKeybord(edit_name, this@PublishActivity)
            }
        }
    }

    private fun againEdit() {
        //如果第一次点击例如加粗，没有焦点时，获取焦点并弹出软键盘
        rich_Editor.focusEditor()
        KeyBoardUtils.openKeybord(edit_name, this@PublishActivity)
    }

    fun selectImage(
        requestCode: Int,
        imageItems: ArrayList<ImageItem>?
    ) {
        val imagePicker: ImagePicker = ImagePicker.getInstance()
        imagePicker.setCrop(false)
        imagePicker.setMultiMode(false)
        imagePicker.setShowCamera(true)
        val intent = Intent(this, ImageGridActivity::class.java)
        intent.putExtra(ImageGridActivity.EXTRAS_IMAGES, imageItems)
        startActivityForResult(intent, requestCode)
    }

    override fun onActivityResult(
        requestCode: Int,
        resultCode: Int,
        data: Intent?
    ) {
        super.onActivityResult(requestCode, resultCode, data)
        if (resultCode == ImagePicker.RESULT_CODE_ITEMS) {
            if (requestCode == 104) {
                selectImages.clear()
                val selects: ArrayList<ImageItem>? =
                    data!!.getSerializableExtra(ImagePicker.EXTRA_RESULT_ITEMS) as ArrayList<ImageItem>?
                selectImages.addAll(selects!!)
                againEdit()
                rich_Editor.insertImage(selectImages[0].path, "dachshund")
                KeyBoardUtils.openKeybord(edit_name, this@PublishActivity)
                rich_Editor.postDelayed(Runnable {
                    if (rich_Editor != null) {
                        rich_Editor.scrollToBottom()
                    }
                }, 200)
            }
        } else if (resultCode == -1) {
            if (requestCode == 11) {
                val outPath = data!!.getStringExtra(EXTRA_OUTPUT_URI)
                if (!TextUtils.isEmpty(outPath)) {
                    val newHtml: String? =
                        rich_Editor.html?.replace(currentUrl, outPath, false)
                    rich_Editor.html = newHtml
                    currentUrl = ""
                }
            }
        }
    }
}